﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Resources;

namespace Chicken4wp.Services
{
    public class StorageService
    {
        private static readonly IsolatedStorageFile FileSystem = IsolatedStorageFile.GetUserStoreForApplication();
        private static readonly string BasePath = "www";
        private static readonly string PluginPath;
        private static readonly string LanguagePath;
        private static readonly string ProxyPath;
        private static readonly string ViewPath;

        static StorageService()
        {
            PluginPath = Path.Combine(BasePath, "plugins");
            LanguagePath = Path.Combine(PluginPath, "languages");
            ProxyPath = Path.Combine(PluginPath, "proxies");
            ViewPath = Path.Combine(BasePath, "views");
            Initialize();
        }

        private static void Initialize()
        {
            if (!FileSystem.DirectoryExists(ViewPath))
            {
                FileSystem.CreateDirectory(ViewPath);
            }
            if (!FileSystem.DirectoryExists(PluginPath))
            {
                FileSystem.CreateDirectory(PluginPath);
            }
            if (!FileSystem.DirectoryExists(LanguagePath))
            {
                FileSystem.CreateDirectory(LanguagePath);
            }
            if (!FileSystem.DirectoryExists(ProxyPath))
            {
                FileSystem.CreateDirectory(ProxyPath);
            }
            CreateViews(Path.Combine(ViewPath, "jquery-1.11.0.min.js"));
            CreateViews(Path.Combine(ViewPath, "ProxySettingFinish.html"));
            //
            CreateViews(Path.Combine(PluginPath, "proxies/baseProxy.js"));
        }

        private static void CreateViews(string path)
        {
            StreamResourceInfo fileResourceStreamInfo = Application.GetResourceStream(new Uri(path, UriKind.Relative));

            using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream))
            {
                byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length);

                using (IsolatedStorageFileStream outFile = FileSystem.OpenFile(path, FileMode.OpenOrCreate))
                {
                    using (var writer = new BinaryWriter(outFile))
                    {
                        writer.Write(data);
                    }
                }
            }
        }

        public Uri GetUri(string view)
        {
            return new Uri(ViewPath + Path.DirectorySeparatorChar + view + ".html", UriKind.Relative);
        }

        public void CreateFile()
        { }
    }
}
